<?php

/**
 * This is the model class for table "{{post}}".
 *
 * The followings are the available model relations:
 * @property Category $category
 */
class Post extends CActiveRecord
{
	const STATUS_PENDING    = 1;
	const STATUS_PROCESSING = 2;
	const STATUS_COMPLETE   = 3;
	
	const VISIBILITY_PUBLIC = 1;
	const VISIBILITY_HIDDEN = 2 ;
	
	public $created_time_from;
	public $created_time_to;
	public $updated_time_from;
	public $updated_time_to;
	
	public $tags;

	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Post the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{post}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('title', 'required', 'on'=>'adminCreate, adminUpdate'),
			array('category_id', 'numerical', 'integerOnly'=>true),
			array('title, slug', 'length', 'max'=>200),
			array('title, slug, content, rating, status, category_id, created_time, updated_time, tags, visibility', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('title, content, rating, status, visibility, category_id, created_time_from, created_time_to, updated_time_from, updated_time_to', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'category' => array(self::BELONGS_TO, 'Category', 'category_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'category_id' => 'Category',
			'created_time_from' => 'From',
			'created_time_to' => 'To',
			'updated_time_from' => 'From',
			'updated_time_to' => 'To',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;
		$criteria->with = 'category';

		$criteria->compare('id',$this->id);
		$criteria->compare('title',$this->title,true);
		$criteria->compare('rating',$this->rating);
		$criteria->compare('status',$this->status);
		$criteria->compare('visibility',$this->visibility);
		$criteria->compare('category_id',$this->category_id);

		if ($this->created_time_from) {
			$from = $this->created_time_from;
			$criteria->addCondition("created_time >= '$from'");
		}

		if ($this->created_time_to) {
			$to = $this->created_time_to.' 23:59:59';
			$criteria->addCondition("created_time <= '$to'");
		}
		
		if ($this->updated_time_from) {
			$from = $this->updated_time_from;
			$criteria->addCondition("updated_time >= '$from'");
		}

		if ($this->updated_time_to) {
			$to = $this->updated_time_to.' 23:59:59';
			$criteria->addCondition("updated_time <= '$to'");
		}
		
		if (isset($_GET['Post'])) {
			if (is_array($_GET['Post']['tags'])) {
				$pt = PostTag::model()->tableName();
				$tags = implode(',', $_GET['Post']['tags']);
				$criteria->join .= " JOIN $pt pt ON pt.post_id=t.id AND pt.tag_id IN ($tags)";
			}
		}

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
			'pagination'=>array(
				'pageSize'=>Yii::app()->params['defaultPageSize'],
			),
			'sort'=>array(
				'defaultOrder'=>'updated_time DESC',
			)
		));
	}
	
	public function getStatusListData() {
		return array(
			self::STATUS_PENDING => 'Pending',
			self::STATUS_PROCESSING => 'Processing',
			self::STATUS_COMPLETE => 'Complete',
		);
	}
	
	public function getRatingListData() {
		$range = array_combine(range(1, 5),range(1, 5));
		return $range;
	}
	
	public function getVisibilityListData() {
		return array(
			self::VISIBILITY_PUBLIC => 'Public',
			self::VISIBILITY_HIDDEN => 'Hidden'
		);
	}

	public function getCategoryListData() {
		$cats = array();
		Category::buildCategoryData($cats, null, 0);
		$result = array();
		foreach($cats as $cat) {
			$result[$cat->id] = $cat->getIndent().$cat->name;
		}
		return $result;
	}
	
	protected function beforeSave() {
		if ($this->isNewRecord)
			$this->created_time = date('Y-m-d H:i:s');
		$this->updated_time = date('Y-m-d H:i:s');
		return parent::beforeSave();
	}
	
	public function getSelectedTagIds() {
		$cmd = $this->dbConnection->createCommand();
		$cmd->select('tag_id')
			->from(PostTag::model()->tableName())
			->where("post_id={$this->id}");
		return $cmd->queryColumn();
	}
}